package com.antler.smt.admin.shiro;

import com.antler.smt.admin.utils.RedisUtil;
import com.antler.smt.constant.DateTimeConstant;
import com.antler.smt.utils.RedisKeyUtil;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.Serializable;

/**
 * RedisShiroSession数据访问对象
 *
 * @author vic
 * @date 2018-03-26 19:43
 */
@Component
public class RedisShiroSessionDAO extends EnterpriseCacheSessionDAO {
    /**
     * redis工具类
     */
    @Autowired
    private RedisUtil redisUtil;

    /**
     * 创建session
     *
     * @param session 会话
     * @return
     */
    @Override
    protected Serializable doCreate(Session session) {
        Serializable sessionId = super.doCreate(session);
        final String key = RedisKeyUtil.getShiroSessionKey(sessionId.toString());
        setShiroSession(key, session);
        return sessionId;
    }

    /**
     * 获取session
     *
     * @param sessionId 会话id
     * @return
     */
    @Override
    protected Session doReadSession(Serializable sessionId) {
        Session session = super.doReadSession(sessionId);
        if (session == null) {
            final String key = RedisKeyUtil.getShiroSessionKey(sessionId.toString());
            session = getShiroSession(key);
        }
        return session;
    }

    /**
     * 更新session
     *
     * @param session 会话
     */
    @Override
    protected void doUpdate(Session session) {
        super.doUpdate(session);
        final String key = RedisKeyUtil.getShiroSessionKey(session.getId().toString());
        setShiroSession(key, session);
    }

    /**
     * 删除session
     *
     * @param session 会话
     */
    @Override
    protected void doDelete(Session session) {
        super.doDelete(session);
        final String key = RedisKeyUtil.getShiroSessionKey(session.getId().toString());
        redisUtil.remove(key);
    }

    /**
     * 根据key获取session
     *
     * @param key 键
     * @return
     */
    private Session getShiroSession(String key) {
        return redisUtil.get(key);
    }

    /**
     * 保存session到redis
     *
     * @param key     键
     * @param session 会话
     */
    private void setShiroSession(String key, Session session) {
        //60分钟过期
        redisUtil.set(key, session, DateTimeConstant.HOUR_S);
    }
}
